package com.pvdnc.tapkit.utils;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.pvdnc.nsocket.log.SLog;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class LifecycleManager implements Application.ActivityLifecycleCallbacks {
    private static final SLog LOG=new SLog(LifecycleManager.class);

    private static final AtomicReference<LifecycleManager> sInstance=new AtomicReference<>();

    public static void systemReady(Application app){
        if(sInstance.get()!=null){
            LOG.e("life cycle listener has been registered already");
            return;
        }
        sInstance.set(new LifecycleManager(app));
    }

    private LifecycleManager(Application app){
        app.registerActivityLifecycleCallbacks(this);
    }

    public static LifecycleManager getInstance(){
        return sInstance.get();
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        if(!mRunningActivityList.contains(activity))
            mRunningActivityList.add(activity);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    private List<Activity> mRunningActivityList=new ArrayList<>();

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        LOG.d("activity:"+activity+" resumed"
                +"("+mRunningActivityList.size()+")");
        if(mRunningActivityList.isEmpty()) {//刚刚有前台Activity
           broadcastForeground();
        }
        if(!mRunningActivityList.contains(activity))
            mRunningActivityList.add(activity);
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {
        LOG.d("activity:"+activity+" paused"
                +"("+mRunningActivityList.size()+")");
        mRunningActivityList.remove(activity);
        if(mRunningActivityList.size()==0) { //刚刚关闭最后一个前台Activity
            broadcastBackground();
        }

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {
        LOG.d("activity:"+activity+" stopped");
        mRunningActivityList.remove(activity);
    }

    private void broadcastForeground(){
        LOG.d("app is going to be foreground");
        AppStatusReceiver.broadcast(AppStatusReceiver.STATUS_FOREGROUND);
    }

    private void broadcastBackground(){
        LOG.d("app is going to be background");
        AppStatusReceiver.broadcast(AppStatusReceiver.STATUS_BACKGROUND);
    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {

    }
}
